package biz

import (
	"context"
	"time"

	"lianzi_gos/internal/mods/mpweixin/dal"
	"lianzi_gos/internal/mods/mpweixin/schema"
	"lianzi_gos/pkg/errors"
	"lianzi_gos/pkg/util"
)

// 联系我们
type Connection struct {
	Trans         *util.Trans
	ConnectionDAL *dal.Connection
}

// Query connections from the data access object based on the provided parameters and options.
func (a *Connection) Query(ctx context.Context, params schema.ConnectionQueryParam) (*schema.ConnectionQueryResult, error) {
	params.Pagination = true

	result, err := a.ConnectionDAL.Query(ctx, params, schema.ConnectionQueryOptions{
		QueryOptions: util.QueryOptions{
			OrderFields: []util.OrderByParam{
				{Field: "sequence", Direction: util.DESC},
				{Field: "created_at", Direction: util.DESC},
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// Get the specified connection from the data access object.
func (a *Connection) Get(ctx context.Context, id string) (*schema.Connection, error) {
	connection, err := a.ConnectionDAL.Get(ctx, id)
	if err != nil {
		return nil, err
	} else if connection == nil {
		return nil, errors.NotFound("", "Connection not found")
	}
	return connection, nil
}

// Create a new connection in the data access object.
func (a *Connection) Create(ctx context.Context, formItem *schema.ConnectionForm) (*schema.Connection, error) {
	connection := &schema.Connection{
		ID:        util.NewXID(),
		CreatedAt: time.Now(),
	}
	connection.UID = util.FromUserID(ctx)
	if err := formItem.FillTo(connection); err != nil {
		return nil, err
	}

	err := a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.ConnectionDAL.Create(ctx, connection); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return connection, nil
}

// Update the specified connection in the data access object.
func (a *Connection) Update(ctx context.Context, id string, formItem *schema.ConnectionForm) error {
	connection, err := a.ConnectionDAL.Get(ctx, id)
	if err != nil {
		return err
	} else if connection == nil {
		return errors.NotFound("", "Connection not found")
	}

	if err := formItem.FillTo(connection); err != nil {
		return err
	}
	connection.UpdatedAt = time.Now()

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.ConnectionDAL.Update(ctx, connection); err != nil {
			return err
		}
		return nil
	})
}

// Delete the specified connection from the data access object.
func (a *Connection) Delete(ctx context.Context, id string) error {
	exists, err := a.ConnectionDAL.Exists(ctx, id)
	if err != nil {
		return err
	} else if !exists {
		return errors.NotFound("", "Connection not found")
	}

	return a.Trans.Exec(ctx, func(ctx context.Context) error {
		if err := a.ConnectionDAL.Delete(ctx, id); err != nil {
			return err
		}
		return nil
	})
}
